package com.sduept.nwld.dataserver.controller.dataview;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.manager.EquipmentCountManager;
import com.sduept.cim.ledger.manager.EquipmentCountManager.EquipmentCountDto;
import com.sduept.nwld.dataserver.util.ExcelUtil;

/**
 * 一、二次设备统计Controller
 * @author RY
 *	主要负责一次、二次设备统计。当无数据时自动从数据表中统计后生成统计数据。
 *	可手动编辑。往年历史数据不可自动统计，只能手动更改。
 */

@Named
@ViewScoped
public class EquipmentCountController extends AbstractController{
	private static final long serialVersionUID = 4801720942776202905L;
	@Autowired
	private EquipmentCountManager ecm;
	@Autowired
	private CommonDocumentProperties pros;
	private String currentYear;
	private String currentVoltage;
	private String newYear;
	private String sourceYear;
	private List<String>existYears = new ArrayList<String>();	//已经统计过的年份列表
	private List<String>sourceYears = new ArrayList<String>();	//数据源年份列表
	private Map<String, List<EquipmentCountDto>>voltagesDto;
	private List<EquipmentCountDto>countList = new ArrayList<EquipmentCountManager.EquipmentCountDto>();
	private EquipmentCountDto current;
	private StreamedContent file;
	private boolean showReGener = true;
	private boolean showDetailInfo = true;
	
	@PostConstruct
	public void init(){
		existYears = ecm.getExistYears();
		int cy = ecm.getCurrentYear();
		currentYear = String.valueOf(cy);
		currentVoltage = "500kV";
		voltagesDto = ecm.generateVoltagesCountDto(cy);
		countList = voltagesDto.get(currentVoltage.replace("kV", ""));
		if (voltagesDto.size() == 0) {
			PrimeFaces.current().executeScript("rc()");
		}
		getRecentYears();
		getSoueceYears();
	}
	
	public void searchCountInfo(){
		current = null;
		String voltage = currentVoltage.replace("kV", "");
		if (voltagesDto.containsKey(voltage)) {
			countList = voltagesDto.get(voltage);
			if (!voltage.equals("500") && !voltage.equals("全网")) {
				for (EquipmentCountDto dto : countList) {
					if (dto.getRank().equals("总调") || dto.getRank().equals("总调直调")) {
						countList.remove(dto);
						break;
					}
				}
			}
		}else{
			addErrorMessage("电压等级不正确！");
		}
	}
	
	public void onRowSelect(SelectEvent event){
		current = (EquipmentCountDto) event.getObject();
	}
	
	public void onYearSelect(SelectEvent event){
		try{
			int year = Integer.valueOf(currentYear);
			showReGener = year == ecm.getCurrentYear();
			voltagesDto = ecm.generateVoltagesCountDto(year);
		}catch (Exception e){
			addErrorMessage("时间格式不正确！");
		}
		searchCountInfo();
	}
	
	public void onVoltageSelect(SelectEvent event){
		if (currentVoltage.equals("500kV") || currentVoltage.equals("全网")) {
			showDetailInfo = true;
		}else{
			showDetailInfo = false;
		}
		searchCountInfo();
	}
	
	/**
	 * 重新生成统计数据
	 */
	public void reCountEquipmentInfo(){
		int year = Integer.valueOf(currentYear);
		if (year != ecm.getCurrentYear()) {
			addErrorMessage("只能重新生成本年的数据！");
			return;
		}
		voltagesDto = ecm.autoGenerateEquipmentCountDto(year);
		countList = voltagesDto.get(currentVoltage.replace("kV", ""));
		addSuccessMessage("统计完毕！");
	}
	
	public void saveEquipmentCouontInfo(){
		ecm.saveOrUpdateCountInfo(current);
		current = null;
		try{
			voltagesDto = ecm.generateVoltagesCountDto(Integer.valueOf(currentYear));
			searchCountInfo();
			addSuccessMessage("保存成功");
		}catch(Exception e){
			addErrorMessage("时间格式错误");
			e.printStackTrace();
		}
	}
	
	public List<String>completeYear(String query){
		return existYears;
	}

	public List<String>completeVoltages(String query){
		List<String>voltages = new ArrayList<String>();
		for (Integer v : ecm.getStandVoltages()) {
			voltages.add(String.valueOf(v)+"kV");
		}
		voltages.add("全网");
		return voltages;
	}
	
	public String getTitle(){
		if (currentVoltage.contains("500")) {
			return currentYear+"年底总调及中调"+currentVoltage+"及以上电网规模";
		}else if(currentVoltage.equals("全网")){
			return currentYear+"年底南方电网规模";
		}
		return currentYear+"年底南方电网"+currentVoltage+"电网规模";
	}
	
	public List<String> getRecentYears(){
		List<String>preYears = new ArrayList<String>();
		int year = ecm.getCurrentYear();
		for (int i = 1; i <= 5; i++) {
			preYears.add(String.valueOf(year-i));
		}
		preYears.removeAll(ecm.getExistYears());
		return preYears;
	}
	
	public void openSourceDialog(){
		int year = 0;
		try{
			year = Integer.valueOf(newYear);
		}catch(NumberFormatException e){
			addErrorMessage("请输入正确的年份！从1970年至本年。");
			return;
		}
		if (year < 1970 || year > ecm.getCurrentYear()) {
			addErrorMessage("请输入正确的年份！从1970年至本年。");
			return;
		}
		if (existYears.contains(year+"")) {
			addErrorMessage("已存在当前年份，无需再次创建！");
			return;
		}
    	PrimeFaces.current().executeScript("PF('importDialog').show()");
	}
	
	public void getSoueceYears(){
		List<String> existYears = ecm.getExistYears();
		sourceYears = existYears;
	}
	
	public void copyCountInfo(){
		int target = 0;
		int source = 0;
		try{
			if (StringUtils.isEmpty(newYear)) {
				target = Integer.valueOf(currentYear);
			}else{
				target = Integer.valueOf(newYear);
			}
			source = Integer.valueOf(sourceYear);
			if (target == source) {
				addErrorMessage("不能导入同一年的数据");
				return;
			}
			ecm.copyCountInfo(source, target);
		}catch(NumberFormatException e){
			addErrorMessage("请指定导入的年份");
			return;
		}catch (SQLException e) {
			addErrorMessage("导入失败");
			return;
		}
		
		hideAddYearDialog();
		if (!StringUtils.isEmpty(newYear)) {
			currentYear = newYear;
		}
		currentVoltage = "500";
		voltagesDto = ecm.generateVoltagesCountDto(Integer.valueOf(currentYear));
		countList = voltagesDto.get(currentVoltage.replace("kV", ""));
		existYears = ecm.getExistYears();
		newYear = "";
		sourceYear = "";
		addSuccessMessage("导入完毕！");
	}
	
	public void hideAddYearDialog(){
    	PrimeFaces.current().executeScript("PF('addYearDialog').hide()");
	}
	
	public String getSummary(String type){
		if (null == countList) return "";
		
		float c = 0;
		for (EquipmentCountDto dto : countList) {
			if (EquipmentCountManager.LINE_TYPE_AC.equals(type)) {
				c+=dto.getAcLine().getCount();
			}else if(EquipmentCountManager.LINE_TYPE_DC.equals(type)){
				c+=dto.getDcLine().getCount();
			}else if(EquipmentCountManager.TRANS_TYPE_CONVERT.equals(type)){
				c+=dto.getConvertTrans().getCount();
			}else if(EquipmentCountManager.TRANS_TYPE_NORMAL.equals(type)){
				c+=dto.getNormalTrans().getCount();
			}else if(EquipmentCountManager.STATION_TYPE_CONVERT.equals(type)){
				c+=dto.getConvertStation().getCount();
			}else if(EquipmentCountManager.STATION_TYPE_NORMAL.equals(type)){
				c+=dto.getNormalStation().getCount();
			}else if("transNormalCount".equals(type)){
				c+=dto.getNormalTrans().getCapacity();
			}else if("dclineCount".equals(type)){
				c+=dto.getDcLine().getLength();
			}else if("aclineCount".equals(type)){
				c+=dto.getAcLine().getLength();
			}
		}
		return String.valueOf(c).replace(".0", "");
	}
	
	/**
	 * 将所有统计数据合并导出到excel中
	 */
	public void export(){
		for (String key : voltagesDto.keySet()) {
			List<EquipmentCountDto> dtos = voltagesDto.get(key);
			dtos.add(ecm.getSummaryData(dtos));
		}
		
		FileOutputStream os = null;
		FileInputStream is = null;
		try {
			os = new FileOutputStream(new File(pros.getExportTempPath()+"equipmentCount.xls"));
			ExcelUtil.writeEquipmentStatisExcel(voltagesDto, os);
			is = new FileInputStream(new File(pros.getExportTempPath()+"equipmentCount.xls"));
			file = new DefaultStreamedContent(is, "xls", currentYear+".xls");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			deleteTempFile();
		}
	}
	
	/**
	 * 5秒后删除缓存文件
	 */
	private void deleteTempFile(){
		Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			
			@Override
			public void run() {
				File f = new File(pros.getExportTempPath()+"equipmentCount.xls");
				if (f.exists()) {
					f.delete();
				}
			}
		};
		timer.schedule(task, 1000 * 5);
	}
	
	public String getCurrentYear() {
		return currentYear;
	}

	public void setCurrentYear(String currentYear) {
		this.currentYear = currentYear;
	}

	public List<String> getExistYears() {
		return existYears;
	}

	public void setExistYears(List<String> existYears) {
		this.existYears = existYears;
	}

	public String getCurrentVoltage() {
		return currentVoltage;
	}

	public void setCurrentVoltage(String currentVoltage) {
		this.currentVoltage = currentVoltage;
	}

	public List<EquipmentCountDto> getCountList() {
		return countList;
	}

	public void setCountList(List<EquipmentCountDto> countList) {
		this.countList = countList;
	}

	public EquipmentCountDto getCurrent() {
		return current;
	}

	public void setCurrent(EquipmentCountDto current) {
		this.current = current;
	}

	public boolean isShowReGener() {
		return showReGener;
	}

	public void setShowReGener(boolean showReGener) {
		this.showReGener = showReGener;
	}

	public String getNewYear() {
		return newYear;
	}

	public void setNewYear(String newYear) {
		this.newYear = newYear;
	}

	public String getSourceYear() {
		return sourceYear;
	}

	public void setSourceYear(String sourceYear) {
		this.sourceYear = sourceYear;
	}

	public List<String> getSourceYears() {
		return sourceYears;
	}

	public void setSourceYears(List<String> sourceYears) {
		this.sourceYears = sourceYears;
	}

	public boolean isShowDetailInfo() {
		return showDetailInfo;
	}

	public void setShowDetailInfo(boolean showDetailInfo) {
		this.showDetailInfo = showDetailInfo;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}
}
